import { baseFormConfig } from '@/components/BaseForm/config';
import { FileImageOutlined, MinusCircleOutlined } from '@ant-design/icons';
import type { DatePickerProps, RadioChangeEvent } from 'antd';
import { DatePicker } from 'antd';
import { Button, Card, Col, Form, message, Radio, Row, Upload, Image, Input } from 'antd';
import Preview from './preview';
import { useRef, useState } from 'react';
import AudioPlayer from './AudioPlayer';
import style from './index.less';
import { ButtonStyle } from '../../../config/globalStyle';
import domtoimage from 'dom-to-image';
import { saveAs } from 'file-saver';
import { Swiper, SwiperSlide } from 'swiper/react';
// Import Swiper styles
// https://swiperjs.com/demos
import './swiper.less';
import 'swiper/swiper-bundle.css';
import FreeMode, { Scrollbar, Mousewheel } from 'swiper';
// 生成图片自动下载为png格式（将dom转为二进制再编译下载）
const getBlobPng = () => {
  const node = document.getElementById('TemplatePreview');
  domtoimage.toBlob(node!).then((blob) => {
    // 调用file-save方法 直接保存图片
    saveAs(blob, '自动保存.png');
  });
};
import TagArray from './tag';

const Template = () => {
  const formRef = useRef<any>(null);
  const [isTurnPage, setIsTurnPage] = useState(true);
  const [holiday, setHoliday] = useState(''); // 放假日期
  const [registrationDay, setRegistrationDay] = useState(''); // 报名日期
  const [schoolDay, setSchoolDay] = useState(''); // 开学日期
  const [quarterDay, setQuarterDay] = useState(''); // 开学日期
  const [uploadVideoList, setUploadVideoList] = useState<any[]>([]);
  const [uploadImageList, setUploadImageList] = useState<any[]>([]);
  const [parentCount, setParentCount] = useState<any>(['科目', '语文', '数学', '英语', '综合']);

  const getChildCount = (val: number) => {
    setParentCount(val);
  };
  console.log(parentCount);

  const onFinish = (values: any) => {
    console.log('Success:', values);
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onTurnPageChange = (e: RadioChangeEvent) => {
    console.log('radio checked', e.target.value);
    setIsTurnPage(e.target.value);
  };
  const props = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    action:
      'http://localhost:8080/api/video/upload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ',
    onChange({ file, fileList }: { file: any; fileList: any }) {
      const { status } = file;
      console.log(fileList);
      if (
        status !==
        'uploadin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                g'
      ) {
        // console.log(file, fileList);
      }
      if (status === 'done') {
        setUploadVideoList(fileList);
        message.success(`${file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
    onDrop(e: any) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    beforeUpload: (file: any) => {
      setUploadVideoList([...uploadVideoList, file]);
      return false;
    },
  };
  const imageProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    action:
      'http://localhost:8080/api/video/upload                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ',
    onChange({ file, fileList }: { file: any; fileList: any }) {
      const { status } = file;
      console.log(fileList);
      if (
        status !==
        'uploadin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                g'
      ) {
        // console.log(file, fileList);
      }
      if (status === 'done') {
        setUploadImageList(fileList);
        message.success(`${file.name} file uploaded successfully.`);
      } else if (status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
    onDrop(e: any) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    beforeUpload: (file: any) => {
      setUploadImageList([...uploadImageList, file]);
      return false;
    },
  };
  /** 修改成符合video组件格式的数组 */
  const toTracks = (listParams: any[]) => {
    let list = Array.isArray(listParams) ? listParams : [listParams];
    list = list.map((item, index) => {
      console.log('listitem', item, index);
      return {
        ...item,
        title: item.name,
        artist: 'Wataboi',
        audioSrc: URL.createObjectURL(list[0]),
        image: 'http://p3.music.126.net/tBTNafgjNnTL1KlZMt7lVA==/18885211718935735.jpg',
      };
    });
    return list;
  };
  const toBlobImage = (listParams: any) => {
    let list = Array.isArray(listParams) ? listParams : [listParams];

    list = list.map((item) => {
      return {
        ...item,
        name: item.name,
        src: URL.createObjectURL(list[0]),
      };
    });

    console.log('blob', list);
    return list;
  };
  const onRemove = (file: any) => {
    const index = uploadVideoList.indexOf(file);
    console.log(index);
    const newFileList = uploadVideoList.slice();
    newFileList.splice(index, 1);
    console.log('newFileList', newFileList);
    setUploadVideoList(newFileList);
  };
  const onImageRemove = (file: any) => {
    const index = uploadImageList.indexOf(file);
    const newFileList = uploadImageList.slice();
    newFileList.splice(index, 1);
    setUploadImageList(newFileList);
  };
  const handlePreview = () => {
    const url = URL.createObjectURL(uploadVideoList[0]);
    const audio = new Audio(url);
    console.log('url', url);
    audio.play();
  };

  const previewProps = {
    parentCount,
    isChanged: true,
    url: uploadImageList[1] ? toBlobImage(uploadImageList[1])[0]?.src : '',
    holiday,
    registrationDay,
    schoolDay,
    quarterDay,
  };

  const onHolidayChange: DatePickerProps['onChange'] = (date, dateString) => {
    setHoliday(dateString);
  };

  const onRegistrationDayChange: DatePickerProps['onChange'] = (date, dateString) => {
    setRegistrationDay(dateString);
  };

  const onSchoolDayChange: DatePickerProps['onChange'] = (date, dateString) => {
    setSchoolDay(dateString);
  };

  const onQuarterChange: DatePickerProps['onChange'] = (date, dateString) => {
    setQuarterDay(dateString);
    console.log(dateString);
  };

  const swiperConfig: Swiper & { modules: any } = {
    direction: 'vertical',
    slidesPerView: 'auto',
    freeMode: true,
    scrollbar: true,
    mousewheel: true,
    modules: [FreeMode, Scrollbar, Mousewheel],
  };

  return (
    <div>
      <Card style={{ height: '1100px', minWidth: '1360px' }}>
        <Row gutter={24} style={{ position: 'relative' }}>
          <Col className={style.leftContainer}>
            {/* <Preview {...previewProps} /> */}
            {isTurnPage ? (
              <Swiper className="mySwiper">
                {uploadImageList.map((item, index) => {
                  console.log(item, toBlobImage(item));
                  return index === 1 ? (
                    <SwiperSlide>
                      <Preview {...previewProps} />
                    </SwiperSlide>
                  ) : (
                    <SwiperSlide>
                      <Preview
                        isChanged={false}
                        url={toBlobImage(uploadImageList[index])[0]?.src}
                      />
                    </SwiperSlide>
                  );
                })}
              </Swiper>
            ) : (
              <div
                style={{
                  height: '1077px',
                  overflow: 'auto',
                }}
              >
                {uploadImageList.map((item, index) => {
                  return index === 1 ? (
                    <Preview {...previewProps} />
                  ) : (
                    <Preview isChanged={false} url={toBlobImage(uploadImageList[index])[0]?.src} />
                  );
                })}
              </div>
            )}
          </Col>
          <Col className={style.rightContainer}>
            <Form
              {...baseFormConfig}
              style={{ width: 500 }}
              ref={formRef}
              name="basic"
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                label="音乐"
                name="title"
                rules={[{ required: true, message: '请上传音乐!' }]}
              >
                <Upload {...props}>
                  <Button type="primary">上传音乐</Button>
                </Upload>
                <div
                  style={{
                    width: '500px',
                    scale: '0.8',
                    marginLeft: -57,
                  }}
                >
                  {uploadVideoList.map((file, index) => {
                    return (
                      <li
                        style={{
                          display: 'flex',
                          flexDirection: 'row',
                          marginTop: '10px',
                        }}
                        key={file.uid}
                      >
                        <AudioPlayer tracks={toTracks(uploadVideoList[index])} />
                        <button
                          onClick={() => onRemove(file)}
                          style={{
                            display: 'flex',
                            top: '0px',
                          }}
                        >
                          <MinusCircleOutlined
                            style={{
                              backgroundColor: 'red',
                              color: 'white',
                              borderRadius: '50%',
                            }}
                          />
                        </button>
                      </li>
                    );
                  })}
                </div>
              </Form.Item>
              <Form.Item
                label="是否翻页"
                name="role"
                rules={[{ required: true, message: '请选择视是否翻页' }]}
                style={{
                  marginTop: '30px',
                  marginBottom: '30px',
                }}
              >
                <Radio.Group
                  onChange={onTurnPageChange}
                  defaultValue={isTurnPage}
                  value={isTurnPage}
                >
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                label="背景上传"
                name="background"
                rules={[{ required: true, message: '请上传背景' }]}
              >
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                    width: '500px',
                  }}
                >
                  <Upload
                    {...imageProps}
                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                    listType="picture"
                    // defaultFileList={[...fileList]}
                  >
                    <div className={style.imageUpload}>
                      <FileImageOutlined
                        style={{
                          color: 'rgba(21, 192, 230, 1)',
                          backgroundColor: 'rgba(21, 192, 230, 0.1)',
                        }}
                      />
                    </div>
                  </Upload>
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                    }}
                    className={style.imageParent}
                  >
                    {uploadImageList.map((item) => {
                      return (
                        <div
                          key={item.name}
                          style={{
                            display: 'flex',
                            flexDirection: 'row',
                          }}
                        >
                          <Image width={100} src={toBlobImage(item)[0].src} />
                          <button
                            onClick={() => onImageRemove(item)}
                            style={{
                              display: 'flex',
                              top: '0px',
                            }}
                          >
                            <MinusCircleOutlined
                              style={{
                                backgroundColor: 'red',
                                color: 'white',
                                borderRadius: '50%',
                              }}
                            />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </Form.Item>
              <Form.Item
                label="放假日期"
                name="holiday"
                rules={[{ required: true, message: '请选择放假日期' }]}
              >
                <DatePicker onChange={onHolidayChange} />
              </Form.Item>
              <Form.Item
                label="报名日期"
                name="registrationDay"
                rules={[{ required: true, message: '请选择报名日期' }]}
              >
                <DatePicker onChange={onRegistrationDayChange} />
              </Form.Item>
              <Form.Item
                label="开学日期"
                name="schoolDay"
                rules={[{ required: true, message: '请选择报名日期' }]}
              >
                <DatePicker onChange={onSchoolDayChange} />
              </Form.Item>
              <Form.Item
                label="季度"
                name="quarterOptions"
                rules={[{ required: true, message: '请选择季度' }]}
              >
                <DatePicker onChange={onQuarterChange} picker="quarter" />
              </Form.Item>
              <Form.Item
                label="填入科目"
                name="array"
                rules={[{ required: true, message: '填入科目' }]}
              >
                {/* https://4x.ant.design/components/tag-cn/ */}
                {/* 动态添加和删除
               预期通过动态添加tag来实现可配置的科目 */}
                <TagArray getCount={getChildCount} />
              </Form.Item>
              {/* <Button onClick={getBlobPng}>测试</Button> */}
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                }}
              >
                <Button key="cancel" className="cancel-button" style={ButtonStyle}>
                  取消
                </Button>
                <Button
                  key="submit"
                  type="primary"
                  className="cancel-button"
                  style={ButtonStyle}
                  onClick={getBlobPng}
                >
                  确定
                </Button>
              </div>
            </Form>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default Template;
